package day52.pet.service.impl;

import day52.basic.commonenum.ErrorCode;
import day52.basic.domain.dto.ConfirmOrderDto;
import day52.basic.exception.CustomException;
import day52.basic.util.AjaxResult;
import day52.pet.domain.OrderPetAcquisition;
import day52.pet.domain.Pet;
import day52.pet.domain.SearchMasterMsg;
import day52.pet.mapper.OrderPetAcquisitionMapper;
import day52.pet.mapper.PetMapper;
import day52.pet.mapper.SearchMasterMsgMapper;
import day52.pet.service.IOrderPetAcquisitionService;
import day52.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Yang
 * @since 2022-12-27
 */
@Service
public class OrderPetAcquisitionServiceImpl extends BaseServiceImpl<OrderPetAcquisition> implements IOrderPetAcquisitionService {
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Override
    @Transactional
    public AjaxResult confirm(ConfirmOrderDto dto) {
        //判断订单状态是否是待处理
        OrderPetAcquisition opa = orderPetAcquisitionMapper.findOne(dto.getId());
        if(opa.getState() != 0){
            throw new CustomException(ErrorCode.ORDER_FINISH.getCode());
        }
        //更新宠物信息
        Pet pet = petMapper.findOne(opa.getPetId());
        //更新成本价
        pet.setCostprice(dto.getMoney());
        petMapper.update(pet);
        //更新订单信息
        opa.setPaytype(dto.getPayType());
        //更新收购金额
        opa.setPrice(dto.getMoney());
        //更新收购订单状态为已完成
        opa.setState(1);
        orderPetAcquisitionMapper.update(opa);
        //更新寻主消息状态
        SearchMasterMsg msg = searchMasterMsgMapper.findOne(opa.getSearchMasterMsgId());
        msg.setState(2);
        searchMasterMsgMapper.update(msg);
        return AjaxResult.me();
    }

    @Override
    @Transactional
    public AjaxResult cancel(Long id) {
        //判断订单状态是否是待处理
        OrderPetAcquisition opa = orderPetAcquisitionMapper.findOne(id);
        if(opa.getState() != 0){
            throw new CustomException(ErrorCode.ORDER_FINISH.getCode());
        }
        //修改收购单的状态
        opa.setState(-1);
        orderPetAcquisitionMapper.update(opa);
        //删狗子
        petMapper.delete(opa.getPetId());
        //置空msg的shopid
        SearchMasterMsg msg = searchMasterMsgMapper.findOne(opa.getSearchMasterMsgId());
        msg.setShopId(null);
        searchMasterMsgMapper.update(msg);
        return AjaxResult.me();
    }
}
